package controllers

import (
	"cld-quick-cli/com"
	"cld-quick-cli/config"
	"cld-quick-cli/logic"
	"cld-quick-cli/pkg"
	"cld-quick-cli/router/middlewares"
	"cld-quick-cli/router/parameters"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"path"
)

// SingleUpload 单文件上传
func SingleUpload() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		// 单文件
		file, err := ctx.FormFile("file")
		sceneType := ctx.PostForm("sceneType")
		if err != nil {
			zap.L().Error(err.Error())
			com.ResponseData(ctx, com.CodeFailed, err)
			return
		}
		if len(sceneType) == 0 {
			com.ResponseData(ctx, com.CodeFailed, "请填写文件场景sceneType")
			return
		}
		dir, err := pkg.MkAllPathDir(config.Config.StaticBaseUrl + config.Config.StaticFileDirPath)
		if err != nil {
			zap.L().Error(err.Error())
			com.ResponseData(ctx, com.CodeFailed, err)
			return
		}
		dst := dir + file.Filename
		// 上传文件至指定的完整文件路径
		err = ctx.SaveUploadedFile(file, dst)
		if err != nil {
			com.ResponseData(ctx, com.CodeFailed, err)
			return
		}
		value, exists := ctx.Get(middlewares.CTX_USER_ID)
		if !exists {
			com.ResponseData(ctx, com.CodeNoAuthError, value)
			return
		}
		userId := value
		// 上传完成后入库！
		//获取文件的后缀名
		extension := path.Ext(file.Filename)
		fileObj := parameters.SingleUploadFile{}
		fileObj.File = file
		fileObj.Name = file.Filename
		fileObj.Path = dst
		fileObj.Size = file.Size
		fileObj.Extension = extension
		fileObj.UploadIp = ctx.ClientIP()
		fileObj.SceneType = sceneType
		fileObj.UploadType = "本地"
		fileObj.BaseUrl = config.Config.StaticBaseUrl
		fileObj.UserId = userId.(string)
		fileObj.FileId = pkg.GenSnowflakeID()
		err = logic.SaveFileDateBaseLogic(&fileObj)
		if err != nil {
			com.ResponseData(ctx, com.CodeFailed, err.Error())
			return
		}
		com.ResponseData(ctx, com.CodeSuccess, gin.H{
			"path":    "/" + dst,
			"file_id": fileObj.FileId,
		})
	}
}

// DownloadFile 文件下载
func DownloadFile() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		fileId := ctx.Param("fileId")
		if len(fileId) == 0 {
			com.ResponseData(ctx, com.CodeParameterError, "无文件id")
			return
		}
		downloadFilePath, err := logic.DownFileLogic(fileId)
		if err != nil {
			com.ResponseData(ctx, com.CodeParameterError, err.Error())
			return
		}
		fmt.Println(downloadFilePath)
		ctx.File(downloadFilePath)
	}
}
